<?php
namespace app\api\controller;
use think\Request;
use think\Session;
use think\Cache;
use app\base\model\{
    Area,
    ReceiveAddress as ReceiveModel,
    SignInLog,
    Coupons,
    UserCoupon,
    Collection,
    Cart,
    User as UserModel,
    LikeVideo,
    IndexModule
};

class User extends Base{
   //地区模型
    protected $area;
    //收货地址模型
    protected $receive;
    //签到记录模型
    protected $signIn;
    //优惠券模型
    protected $coupons;
    //用户优惠券模型
    protected $user_coupons;
    //商品收藏模型
    protected $collect;
    //购物车模型
    protected $cart;
    //用户模型
    protected $user;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->area = new Area();
        $this->receive = new ReceiveModel();
        $this->signIn  = new SignInLog();
        $this->coupons = new Coupons();
        $this->user_coupons = new UserCoupon();
        $this->collect      = new Collection();
        $this->cart      = new Cart();
        $this->user = new UserModel();
    }
  /**
   *获取地区列表
   * return json
   */
    public function getArea(){
      if(empty($this->userInfo)){
          $msg=checkMsg(LOGIN_ERROR);
          return ['message'=>$msg];
      }
      $pid=$this->request->post('pid',0);
      $area_list=$this->area->where(['pid'=>$pid])->select();
       if(empty($area_list)){
           $result['message']=checkMsg(GET_DATA_FAILE);
       }else{
           $result['message']=checkMsg(GET_DATA_SUCCESS);
           $result['area_list']=$area_list;
       }
       return $result;
    }
    /**
     *获取用户信息
     * return json
     */
    public function getUserInfo(){
        if(empty($this->userInfo)){
             $msg['message']=checkMsg(LOGIN_ERROR);
            return $msg;
        }
        $userInfo=$this->user->where(['uid'=>$this->user_id])->find();
        $msg['message']=checkMsg(GET_DATA_SUCCESS);
        $msg['info']=$userInfo;
        return $msg;
    }
    /**
     *用户的收货地址列表
     * return json
     */
    public function getAddressList(){
        if(empty($this->userInfo)){
            $msg=checkMsg(LOGIN_ERROR);
            return ['message'=>$msg];
        }
        $list=$this->receive->where(['uid'=>$this->userInfo['uid']])->order('id','desc')->select();
        if(!empty($list)){
            $msg=checkMsg(GET_DATA_SUCCESS);
            $result['message']=$msg;
            $result['list']=$list;
        }else{
            $msg=checkMsg(GET_DATA_FAILE);
            $result['message']=$msg;
        }
        return $result;
    }
    /**
     *增加或修改收货地址
     *return json
     */
  public function addOrEditeAddress(){
      if(empty($this->userInfo)){
          $msg=checkMsg(LOGIN_ERROR);
          return ['message'=>$msg];
      }
      $input =$this->request->post();

      $check_error=$this->validate($input,'Address');
      if($check_error!==true){
          $msg=checkMsg($check_error);
          return ['message'=>$msg];
      }
      $data=[
          'uid'        =>$this->userInfo['uid'],
          'user_name'  =>$input['user_name'],
          'phone'      =>$input['phone'],
          'province'   =>$input['province'],
          'city'       =>$input['city'],
          'district'   =>$input['district'],
          'address'    =>$input['address'],
      ];
      if(!isset($input['address_id'])){  //增加收货地址
          $data['add_time']=time();
          $res=$this->receive->insertGetId($data);
          if($res){
              $msg['message']=checkMsg(ADD_SUCCESS);
          }else{
              $msg['message']=checkMsg(ADD_FAIL);
          }
      }else{  //修改收货地址
          $data['update_time']=time();
          $res=$this->receive->save($data,['id'=>$input['address_id']]);
          if($res){
              $msg['message']=checkMsg(UPDATE_DATA_SUCCESS);
          }else{
              $msg['message']=checkMsg(UPDATE_DATA_FAIL);
          }
      }
       return $msg;
  }
 /**
  *删除收货地址
  * return json
  */
     public function deleteAddress(){
     if(empty($this->userInfo)){
         $msg=checkMsg(LOGIN_ERROR);
         return ['message'=>$msg];
     }
     $address_id=$this->request->post('address_id');
     if(empty($address_id)){
         $msg=checkMsg(CANSHU_ERROR);
         return ['message'=>$msg];
     }
     $res=$this->receive->where(['id'=>$address_id,'uid'=>$this->userInfo['uid']])->delete();
     if($res){
         $msg=checkMsg(DELETE_DATA_SUCCESS);
     }else{
         $msg=checkMsg(DELETE_DATA_FAIL);
     }
     return ['message'=>$msg];
 }
 /**
  *用户签到领遇策币
  * return josn
  */
  public function signIn(){
      if(empty($this->userInfo)){
          $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
     $where=[
         'uid' =>$this->userInfo['uid'],
         'log_date' =>date('Y-m-d',time()),
     ];
      $count=$this->signIn->where($where)->count();
      if($count>0){
          $msg['message']=checkMsg(TODAY_SIGNED);
          return $msg;
      }
      $userInfo=$this->user->where(['uid'=>$this->user_id])->find();
      $user_res=$this->user->save(['yc_coin'=>$userInfo['yc_coin']+10],['uid'=>$this->user_id]);
      if($user_res){
          $sign_data=[
              'uid'  => $this->user_id,
              'log_date' =>date("Y-m-d",time()),
              'log_add_time' =>time()
          ];
          $sign_res=$this->signIn->insertGetId($sign_data);
          $last_day_res=$this->signIn->where(['log_date'=>date('Y-m-d',time()-24*3600),'uid'=>$this->user_id])->find();
          if(!empty($last_day_res) && $last_day_res['count_days']!=7){
               $this->signIn->save(['count_days'=>$last_day_res['count_days']+1],['log_id'=>$sign_res]);
          }
          $userInfo=$this->user->where(['uid'=>$this->user_id])->find();
          $msg['message']=checkMsg(SIGN_SUCCESS);
          $msg['yc_coin']=$userInfo['yc_coin'];
      }else{
          $msg['message']=checkMsg(SIGN_FAIL);
      }
     return $msg;
  }
  /**
   *优惠券列表
   *return json
   */
  public function couponsList(){
    $list=$this->coupons->select();
    if(empty($this->userInfo)){
         $msg['message']=checkMsg(LOGIN_ERROR);
        return $msg;
    }
    if(empty($list)){
        $result['message']=checkMsg(GET_DATA_FAILE);
    }else{
        foreach($list as $key=>$value){
             $value['end_time']=strtr($value['end_time'],'.','/');
            $end_time=strtotime($value['end_time'].' 23:59:59');
            if(time()>$end_time){
              unset($list[$key]);
            }
            $value['end_time']=strtr($value['end_time'],'/','.');
        }
        if(empty($list)){
            $result['message']=checkMsg(GET_DATA_FAILE);
        }else{
            $result['message']=checkMsg(GET_DATA_SUCCESS);
            $result['list']=$list;
        }
    }
    return $result;
  }
  /**
   *用户领取优惠券
   * return json
   */
  public function receiveCoupon(){
      if(empty($this->userInfo)){
          $msg=checkMsg(LOGIN_ERROR);
          return ['message'=>$msg];
      }
      $cid = $this->request->post('cid');
      if(empty($cid)){
          $msg=checkMsg(CANSHU_ERROR);
          return ['message'=>$msg];
      }
      $userInfo=$this->user->where(['uid'=>$this->user_id])->find();
      $couponInfo=$this->coupons->where(['c_id'=>$cid])->find();
      if($userInfo['yc_coin']<$couponInfo['yc_coin']){
            $msg['message']=checkMsg(YUCE_ICON_LESS);
          return $msg;
      }else{
          $data=[
              'uid' => $this->user_id,
              'cid' => $cid,
              'add_time' => time()
          ];
         $res=$this->user_coupons->insertGetId($data);
         if($res){
             $yc_coin=$userInfo['yc_coin']-$couponInfo['yc_coin'];
             $this->user->save(['yc_coin'=>$yc_coin],['uid'=>$this->user_id]);
             $msg['message']=checkMsg(RECEIVE_SUCCESS);
         }else{
             $msg['message']=checkMsg(RECEIVE_FAIL);
         }
         return $msg;
      }
  }
  /**
   *用户优惠券列表
   * return json
   */
  public function userCouponList(){
      if(empty($this->userInfo)){
           $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $list=$this->user_coupons->getCouponsList($this->user_id);
     if(empty($list)){
         $msg['message']=checkMsg(GET_DATA_FAILE);
     }else{
         foreach($list as $key=>$value){
             $value['end_time']=strtr($value['end_time'],'.','/');
             $end_time=strtotime($value['end_time'].' 23:59:59');
             if(time()>$end_time){
                unset($list[$key]);
             }
             $value['end_time']=strtr($value['end_time'],'/','.');
         }
         if(empty($list)){
             $msg['message']=checkMsg(GET_DATA_FAILE);
         }else{
             $msg['message']=checkMsg(GET_DATA_SUCCESS);
             $msg['list']=$list;
         }
     }
     return $msg;
  }
  /**
   *获取签到banner图
   *return json
   */
  public function getSignBanner(){
      if(empty($this->userInfo)){
          $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $indexModule = new IndexModule();
      $banner=$indexModule->where(['m_id'=>4])->find();
      if(!empty($banner)){
          $msg['message']=checkMsg(GET_DATA_SUCCESS);
          return $msg;
      }else{
          $msg['message']=checkMsg(GET_DATA_FAILE);
      }
      return $msg;
  }
  /**
   *我的收藏列表
   * return json
   */
  public function getCollectList(){
      if(empty($this->userInfo)){
           $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $pageNo   =$this->request->post('pageNo',1);
      $pageSize =$this->request->post('pageSize',10);
      $type     =$this->request->post('type',1); //1:商品 2:视频
      if($type==1){
          $collectList=$this->collect->getCollectList($this->user_id,$pageNo,$pageSize);
      }else{
          $like_video=new LikeVideo();
          $collectList =$like_video->where(['user_id'=>$this->user_id])->select();
      }
      if(!empty($collectList)){
          $msg['message']=checkMsg(GET_DATA_SUCCESS);
          $msg['list']=$collectList;
      }else{
          $msg['message']=checkMsg(GET_DATA_FAILE);
      }
      return $msg;
  }
  /**
   *添加商品收藏
   * return json
   */
  public function addCollection(){
      if(empty($this->userInfo)){
           $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $goods_id = $this->request->post('goods_id');
      $cart_id  = $this->request->post('cart_id',0);
      if(empty($goods_id)){
           $msg['message']=checkMsg(CANSHU_ERROR);
          return $msg;
      }
      $where=[
          'user_id'  =>$this->user_id,
          'goods_id' =>$goods_id
      ];
      $count=$this->collect->where($where)->count();
      if($count>0){
           $msg['message']=checkMsg(CANNOT_COLLECT_RE);
          return $msg;
      }
      $data=[
          'user_id'  =>$this->user_id,
          'goods_id' =>$goods_id,
          'add_time' =>time()
      ];
      $res=$this->collect->insertGetId($data);
      if($res){
          if(!empty($cart_id)){
              $cartModel=new Cart();
              $cartModel->where(['user_id'=>$this->user_id,'cart_id'=>$cart_id])->delete();
          }
           $msg['message']=checkMsg(COLLECT_SUCCESS);
          return $msg;
      }else{
           $msg['message']=checkMsg(COLLECT_FAIL);
          return $msg;
      }
  }
  /**
   *删除我的收藏
   * return json
   */
  public function deleteCollect(){
      if(empty($this->userInfo)){
           $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $ids=$this->request->post('ids/a');
      $type=$this->request->post('type',1); //1:商品 2:视频
      if(empty($ids)){
           $msg['message']=checkMsg(CANSHU_ERROR);
          return $msg;
      }
      $likeVideo= new LikeVideo();
      if($type==1){
          $res=$this->collect->where(['user_id'=>$this->user_id,'id'=>['in',$ids]])->delete();
      }else{
          $res=$likeVideo->where(['user_id'=>$this->user_id,'id'=>['in',$ids]])->delete();
      }
      if($res){
          $msg['message']=checkMsg(DELETE_COLLECT_SUCCESS);
      }else{
          $msg['message']=checkMsg(DELETE_DATA_FAIL);
      }
      return $msg;
  }
  /**
   *向旧手机发送验证码
   * return json
   */
   public function sendCodeToOldPhone(){
       if(empty($this->userInfo)){
            $msg['message']=checkMsg(LOGIN_ERROR);
           return $msg;
       }
       $old_phone = $this->request->post('old_phone');
       if(empty($old_phone)){
            $msg['message']=checkMsg(CANSHU_ERROR);
           return $msg;
       }
       $userInfo=$this->user->where(['uid'=>$this->user_id])->find();
       if($old_phone != $userInfo['phone']){
            $msg['message']=checkMsg(OLD_PHONE_EORR);
           return $msg;
       }else{
           $code=rand(1000,9999);
           $cache_data=[
               'phone' => $old_phone,
               'send_time' =>time(),
               'code'     =>$code
           ];
           Cache::set($old_phone,$cache_data,'300');
           $data =[$code,'5'];
           $send_res=$this->sendMobileCode($old_phone,$data,$this->tempId);
           if($send_res['code']==1){
               $msg['message']=checkMsg(CHECK_CODE_SEND_SUCCESS);
           }else{
               $msg['message']=checkMsg(CHECK_CODE_SEND_FAIL);
           }
           return $msg;
       }
   }
   /**
    *向新手机号码发送验证码
    * return json
    */
  public function sendCodeToNewPhone(){
      if(empty($this->userInfo)){
           $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $new_phone=$this->request->post('new_phone');
      if(empty($new_phone)){
           $msg['message']=checkMsg(CANSHU_ERROR);
          return $msg;
      }
      $phone_count=$this->user->where(['phone'=>$new_phone])->count();
      if($phone_count>0){
           $msg['message']=checkMsg(PHONE_IS_EXITE);
           return $msg;
      }else{
          $code=rand(1000,9999);
          $cache_data=[
              'phone' => $new_phone,
              'send_time' =>time(),
              'code'     =>$code
          ];
          Cache::set($new_phone,$cache_data,'300');
          $data =[$code,'5'];
          $tempId=$this->tempId;
          $send_res=$this->sendMobileCode($new_phone,$data,$tempId);
          if($send_res['code']==1){
              $msg['message']=checkMsg(CHECK_CODE_SEND_SUCCESS);
          }else{
              $msg['message']=checkMsg(CHECK_CODE_SEND_FAIL);
          }
          return $msg;
      }
  }
  /**
   *修改或绑定用户的手机号码
   * return json
   */
  public function editeOrBindUserPhone(){
      if(empty($this->userInfo)){
           $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
     $phone=$this->request->post('phone');
      if(empty($phone)){
           $msg['message']=checkMsg(CANSHU_ERROR);
          return $msg;
      }
      $count=$this->user->where(['phone'=>$phone])->count();
      if($count>0){
          $msg['message']=checkMsg(PHONE_IS_EXITE);
          return $msg;
      }
      $res=$this->user->save(['phone'=>$phone],['uid'=>$this->user_id]);
      if($res){
           $msg['message']=checkMsg(EDITE_PHONE_SUCCESS);
          return $msg;
      }else{
           $msg['message']=checkMsg(EDITE_PHONE_FAIL);
          return $msg;
      }
  }
  /**
   *修改用户登录密码
   * return json
   */
  public function editePassword(){
      if(empty($this->userInfo)){
           $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $old_password=$this->request->post('old_password');
      $new_password=$this->request->post('new_password');
      $re_password =$this->request->post('re_password');
      if(empty($old_password) || empty($new_password) || empty($re_password)){
           $msg['message']=checkMsg(CANSHU_ERROR);
          return $msg;
      }
      if($new_password != $re_password){
           $msg['message']=checkMsg(PASSWORD_DIFF);
          return $msg;
      }
      $userInfo=$this->user->where(['uid'=>$this->user_id])->find();
      if(MD5($old_password)!=$userInfo['password']){
          $msg['message']=checkMsg(PASSWORD_ERROR);
          return $msg;
      }
     $res=$this->user->save(['password'=>MD5($new_password)],['uid'=>$this->user_id]);
     if($res){
          $msg['message']=checkMsg(EDITE_PASSWORD_SUCCESS);
     }else{
          $msg['message']=checkMsg(EDITE_PASSWORD_FAIL);
     }
     return $msg;
  }
  /**
   *设置用户的登录密码
   * return json
   */
  public function setPassword(){
      if(empty($this->userInfo)){
           $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $password=$this->request->post('password');
      $re_password =$this->request->post('re_password');
      if(empty($password) || empty($re_password)){
           $msg['message']=checkMsg(CANSHU_ERROR);
          return $msg;
      }
      if($password != $re_password){
           $msg['message']=checkMsg(PASSWORD_DIFF);
          return $msg;
      }
      $res=$this->user->save(['password'=>MD5($password)],['uid'=>$this->user_id]);
      if($res){
           $msg['message']=checkMsg(SET_PASSWORD_SUCCESS);
      }else{
           $msg['message']=checkMsg(SET_PASSWORD_FAIL);
      }
      return $msg;
  }
  /**
   *修改用户昵称
   * return json
   */
  public function editeUserName(){
      if(empty($this->userInfo)){
           $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $user_name = $this->request->post('user_name');
      $res=$this->user->save(['user_name'=>$user_name],['uid'=>$this->user_id]);
      if($res){
           $msg['message']=checkMsg(UPDATE_DATA_SUCCESS);
      }else{
           $msg['message']=checkMsg(UPDATE_DATA_FAIL);
      }
      return $msg;
  }
  /**
   *用户购物车列表
   * return json
   */
  public function cartList(){
      if(empty($this->userInfo)){
           $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $type=$this->request->post('type',0); //  0:全部商品 1:降价商品
      $result=$this->cart->cartList($this->user_id,$type);
      return $result;
  }
  /**
   *忘记密码
   * return json
   */
  public function forgetPassword(){
   $phone      = $this->request->post('phone');
   $password   = $this->request->post('password');
   $re_password= $this->request->post('re_password');
   if(empty($phone) || empty($password) || empty($re_password)){
        $msg['message']=checkMsg(CANSHU_ERROR);
       return $msg;
   }
   if($password != $re_password){
        $msg['message']=checkMsg(PASSWORD_DIFF);
       return $msg;
   }
   $data=[
       'password' =>MD5($password)
   ];
   $where=[
       'phone'  =>$phone
   ];
   $res=$this->user->save($data,$where);
   if($res){
        $msg['message']=checkMsg(UPDATE_DATA_SUCCESS);
   }else{
        $msg['message']=checkMsg(UPDATE_DATA_FAIL);
   }
   return $msg;
  }
}